<?php
namespace App\Think\SdkGame;

class KY{

    // 后台地址：https://ht.ky039.com:7988/default
    // 代理ID:64666
    // 账号：lxgl
    // 密码：lxgl168!@#

    // 最新主API域名： https://api.ky039.com/channelHandle
    // 最新主拉单域名： https://record.ky039.com/getRecordHandle
    // 最新主后台域名（登录账密不变）： https://ht.ky039.com:7988/default

    // GLB接口（AnycostIP，接口IP地址固定）
    // 备用API域名：https://api.ky8018.com/channelHandle
    // 备用拉单域名：https://record.ky8018.com/getRecordHandle
    // 备用后台域名（登录账密不变）：https://ht.ky8018.com/default
    // Deakey: AFC46EA1A64E66A0
    // Md5key: 3294DFDC4F16E6B5
    
    public function __construct()
    {
        // api地址
        $this->api_url = 'https://api.ky039.com/channelHandle';
        $this->pull_url = 'https://record.ky039.com/getRecordHandle';
        $this->agent_id = '64666';

        $this->Deakey = 'AFC46EA1A64E66A0';
        $this->Md5key = '3294DFDC4F16E6B5';
        $this->plat_type = 'KY';
    }

    /**
     * 注册
     */
    public function register($param){
        $req_data = array(
            's' => 0,
            'account'  => $param['account'],
            'money'    => 0,
            'orderid'  => $this->agent_id.date('yyyyMMddHHmmss',time()).'000'.$param['account'],
            'ip'       => request()->ip(),
            'lineCode' =>'ky001',
            'KindID'   => 0
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 获取登录链接
     */
    public function login($param){
        // $reg_res = $this->register($param);
        // if($reg_res['code'] == -1) return $reg_res;
        $req_data = array(
            's' => 0,
            'account'  => $param['account'],
            'money'    => 0,
            'orderid'  => $this->agent_id.date('yyyyMMddHHmmss',time()).'000'.$param['account'],
            'ip'       => request()->ip(),
            'lineCode' =>'ky001',
            'KindID'   => 0
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($url);
        return ['code'=>1, 'url'=>$res['url'] ];
    }
    /**
     * 获取余额
     */
    public function balance($param){
        $req_data = array(
            's' => 1,
            'account'  => $param['account'],
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($url);
        return [ 'code'=>$res['code'], 'balance'=>(float)$res['money'] ];
    }

    /**
     * 转入资金(上分)
     */
    public function transIn($param){
        $req_data = array(
            's' => 2,
            'account'  => $param['account'],
            'money'    => $param['money'],
            'orderid'  => $this->agent_id.date('yyyyMMddHHmmss',time()).'000'.$param['account'],
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 转出资金(下分)
     */
    public function transOut($param){
        $req_data = array(
            's' => 3,
            'account'  => $param['account'],
            'money'    => $param['money'],
            'orderid'  => $this->agent_id.date('yyyyMMddHHmmss',time()).'000'.$param['account'],
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($url);
        return $res;
    }
    /**
     * 可转出资金查询(下分额度)
     */
    public function transOutInfo($param){
        $req_data = array(
            'action' => 15,
            'ts'     => time()*1000,
            'parent' => $this->parent,
            'uid'    => $param['account']
        );
        $url = $this->build_request($req_data);
        $res = $this->sendRequest($url);
        return $res;
    }

    /**
     * 游戏注单拉取
     */
    public function gameLogSync($param){
        $req_data = array(
            's' => 6,
            "startTime" => strtotime($param['startTime'])*1000,
            "endTime"   => strtotime($param['endTime'])*1000,
        );
        $url = $this->build_request($req_data, 'pull');
        $res = $this->sendRequest($url);
        
        //数据返回处理
        $list = @$res['list'];
        $rs = $raw_data = [];
        $status = 1;
        if(is_array($list['GameID']) && count($list['GameID']) > 0){
            $list_keys = array_keys($list);
            foreach ($list['GameID'] as $k => $v) {
                //遍历数组
                $_tmp = [];
                foreach ($list_keys as $lk) $_tmp[$lk] = $list[$lk][$k];
                //流水
                // $money_valid = $_tmp['Profit'] > 0 ? $_tmp['Profit'] : $_tmp['AllBet'];
                if($_tmp['Profit'] < 0)  $money_valid = -$_tmp['Profit'];
                if($_tmp['Profit'] >= 0) $money_valid = $_tmp['Profit']<$_tmp['AllBet'] ? $_tmp['Profit'] : $_tmp['AllBet'];
                //游戏记录处理
                $rs[$k] = [
                    'plat_type'     => $this->plat_type,
                    'game_type'     => $_tmp['ServerID'],
                    'game_name'     => @$this->game_name($_tmp['ServerID']),
                    'game_user'     => ltrim($_tmp['Accounts'], $this->agent_id.'_'),
                    'bet_id'        => $_tmp['GameID'],
                    'money_bet'     => $_tmp['AllBet'],
                    'money_valid'   => $money_valid,
                    'money_winlose' => $_tmp['Profit'],
                    'money_fee'     => $_tmp['Revenue'],
                    'createtime'    => strtotime($_tmp['GameStartTime']),
                    'updatetime'    => strtotime($_tmp['GameEndTime']),
                    'status'        => $status,
                ];
                //源数据处理
                $raw_data[$k] = $_tmp;
                $raw_data[$k]['plat_type'] = $this->plat_type;
                $raw_data[$k]['bet_id']    = $_tmp['GameID'];
                $raw_data[$k]['status']    = $status;
                $raw_data[$k]['updatetime'] = strtotime($_tmp['GameEndTime']);
            }
        }
        $res['list'] = $rs;
        $res['raw_data']  = $raw_data;
        $res['code'] = $res['code'] == -16 ? 1 : $res['code'];
        return $res;
    }



    /**
     * 业务 ======== start =========//
     */
    private function bet_status($status){
        return $status;
    }

    //游戏列表
    public function game_list(){
        $list = [
            '3600'=>'德州扑克新手房',
            '3601'=>'德州扑克初级房',
            '3602'=>'德州扑克中级房',
            '3603'=>'德州扑克高级房',
            '3700'=>'德州扑克财大气粗房',
            '3701'=>'德州扑克腰缠万贯房',
            '3702'=>'德州扑克挥金如土房',
            '3703'=>'德州扑克富贵逼人房',
            '7201'=>'二八杠体验房',
            '7202'=>'二八杠初级房',
            '7203'=>'二八杠中级房',
            '7204'=>'二八杠高级房',
            '7205'=>'二八杠至尊房',
            '7206'=>'二八杠王者房',
            '8301'=>'抢庄牛牛体验房',
            '8302'=>'抢庄牛牛初级房',
            '8303'=>'抢庄牛牛中级房',
            '8304'=>'抢庄牛牛高级房',
            '8305'=>'抢庄牛牛至尊房',
            '8306'=>'抢庄牛牛王者房',
            '2201'=>'炸金花体验房',
            '2202'=>'炸金花初级房',
            '2203'=>'炸金花中级房',
            '2204'=>'炸金花高级房',
            '8601'=>'三公体验房',
            '8602'=>'三公初级房',
            '8603'=>'三公中级房',
            '8604'=>'三公高级房',
            '8605'=>'三公至尊房',
            '8606'=>'三公王者房',
            '9001'=>'龙虎体验房',
            '9002'=>'龙虎初级房',
            '9003'=>'龙虎中级房',
            '9004'=>'龙虎高级房',
            '6001'=>'21点体验房',
            '6002'=>'21点初级房',
            '6003'=>'21点中级房',
            '6004'=>'21点高级房',
            '8701'=>'通比牛牛体验房',
            '8702'=>'通比牛牛初级房',
            '8703'=>'通比牛牛中级房',
            '8704'=>'通比牛牛高级房',
            '8705'=>'通比牛牛至尊房',
            '8706'=>'通比牛牛王者房',
            '8801'=>'欢乐红包体验房',
            '8802'=>'欢乐红包初级房',
            '8803'=>'欢乐红包中级房',
            '8804'=>'欢乐红包高级房',
            '2301'=>'极速炸金花新手房',
            '2302'=>'极速炸金花初级房',
            '2303'=>'极速炸金花中级房',
            '2304'=>'极速炸金花高级房',
            '7301'=>'抢庄牌九新手房',
            '7302'=>'抢庄牌九初级房',
            '7303'=>'抢庄牌九中级房',
            '7304'=>'抢庄牌九高级房',
            '7305'=>'抢庄牌九至尊房',
            '7306'=>'抢庄牌九王者房',
            '6101'=>'斗地主体验房',
            '6102'=>'斗地主初级房',
            '6103'=>'斗地主中级房',
            '6104'=>'斗地主高级房',
            '6301'=>'十三水常规场新手房',
            '6302'=>'十三水常规场初级房',
            '6303'=>'十三水常规场中级房',
            '6304'=>'十三水常规场高级房',
            '6305'=>'十三水极速场新手房',
            '6306'=>'十三水极速场初级房',
            '6307'=>'十三水极速场中级房',
            '6308'=>'十三水极速场高级房',
            '3801'=>'幸运五张体验房',
            '3802'=>'幸运五张初级房',
            '3803'=>'幸运五张中级房',
            '3804'=>'幸运五张高级房',
            '3901'=>'射龙门经典房',
            '3902'=>'射龙门暴击房',
            '9101'=>'百家乐体验房',
            '9102'=>'百家乐初级房',
            '9103'=>'百家乐中级房',
            '9104'=>'百家乐高级房',
            '9201'=>'森林舞会体验房',
            '9202'=>'森林舞会初级房',
            '9203'=>'森林舞会中级房',
            '9204'=>'森林舞会高级房',
            '9301'=>'百人牛牛体验房',
            '9302'=>'百人牛牛初级房',
            '9303'=>'百人牛牛中级房',
            '9304'=>'百人牛牛高级房',
            '19501'=>'万人炸金花体验房',
            '19502'=>'万人炸金花初级房',
            '19503'=>'万人炸金花中级房',
            '19504'=>'万人炸金花高级房',
            '6501'=>'血流成河体验房',
            '6502'=>'血流成河初级房',
            '6503'=>'血流成河中级房',
            '6504'=>'血流成河高级房',
            '8901'=>'看牌抢庄牛牛体验房',
            '8902'=>'看牌抢庄牛牛初级房',
            '8903'=>'看牌抢庄牛牛中级房',
            '8904'=>'看牌抢庄牛牛高级房',
            '8905'=>'看牌抢庄牛牛至尊房',
            '8906'=>'看牌抢庄牛牛王者房',
            '7401'=>'二人麻将体验房',
            '7402'=>'二人麻将初级房',
            '7403'=>'二人麻将中级房',
            '7404'=>'二人麻将高级房',
            '13501'=>'幸运转盘',
            '13502'=>'幸运转盘',
            '13503'=>'幸运转盘',
            '19401'=>'金鲨银鲨体验房',
            '19402'=>'金鲨银鲨初级房',
            '19403'=>'金鲨银鲨中级房',
            '19404'=>'金鲨银鲨高级房',
            '19601'=>'奔驰宝马体验房',
            '19602'=>'奔驰宝马初级房',
            '19603'=>'奔驰宝马中级房',
            '19604'=>'奔驰宝马高级房',
            '19801'=>'百人骰宝体验房',
            '19802'=>'百人骰宝初级房',
            '19803'=>'百人骰宝中级房',
            '19804'=>'百人骰宝高级房',
            '18101'=>'单挑牛牛体验房',
            '18102'=>'单挑牛牛初级房',
            '18103'=>'单挑牛牛中级房',
            '18104'=>'单挑牛牛高级房',
            '18105'=>'单挑牛牛至尊房',
            '18106'=>'单挑牛牛王者房',
            '19901'=>'炸金牛体验房',
            '19902'=>'炸金牛初级房',
            '19903'=>'炸金牛中级房',
            '19904'=>'炸金牛高级房',
            '19905'=>'炸金牛至尊房',
            '19906'=>'炸金牛王者房',
            '18501'=>'押宝抢庄牛牛体验房',
            '18502'=>'押宝抢庄牛牛初级房',
            '18503'=>'押宝抢庄牛牛中级房',
            '18504'=>'押宝抢庄牛牛高级房',
            '18505'=>'押宝抢庄牛牛至尊房',
            '18506'=>'押宝抢庄牛牛王者房',
            '5101'=>'人鱼港口',
            '5102'=>'海王遗迹',
            '5103'=>'伟大航道',
            '16601'=>'血战到底体验房',
            '16602'=>'血战到底初级房',
            '16603'=>'血战到底中级房',
            '16604'=>'血战到底高级房',
            '19701'=>'五星宏辉体验房',
            '19702'=>'五星宏辉初级房',
            '19703'=>'五星宏辉中级房',
            '19704'=>'五星宏辉高级房',
            '18601'=>'赌场扑克体验房',
            '18602'=>'赌场扑克初级房',
            '18603'=>'赌场扑克中级房',
            '18604'=>'赌场扑克高级房',
            '13701'=>'港式梭哈新手房',
            '13702'=>'港式梭哈初级房',
            '13703'=>'港式梭哈中级房',
            '13704'=>'港式梭哈高级房',
            '16901'=>'血战骰宝体验房',
            '16902'=>'血战骰宝初级房',
            '16903'=>'血战骰宝中级房',
            '16904'=>'血战骰宝高级房',
            '18901'=>'水果机体验房',
            '18902'=>'水果机初级房',
            '18903'=>'水果机中级房',
            '18904'=>'水果机高级房',
            '16101'=>'幸运夺宝白银宝箱',
            '16102'=>'幸运夺宝黄金宝箱',
            '16103'=>'幸运夺宝铂金宝箱',
            '16104'=>'幸运夺宝钻石宝箱',
            '19301'=>'鱼虾蟹体验房',
            '19302'=>'鱼虾蟹初级房',
            '19303'=>'鱼虾蟹中级房',
            '19304'=>'鱼虾蟹高级房',
            '81301'=>'跑得快体验房',
            '81302'=>'跑得快初级房',
            '81303'=>'跑得快中级房',
            '81304'=>'跑得快高级房',
        ];
        return $list;
    }
    //游戏名称
    public function game_name($gameid){
        $list = $this->game_list();
        return isset($list[$gameid]) ? $list[$gameid] : '未知游戏';
    }


    /**
     * --------------
     * 内部方法
     * --------------
     */
    private function sendRequest($url,$post_data=array(), $req_type=0){
        $ch = curl_init();
        //POST
        if($req_type == 1){ 
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        }else{
            $url = $url;
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $contents = curl_exec($ch);
        curl_close($ch);
        $contents = json_decode($contents, true);
        //业务处理
        $res = $contents['d'];
        if(!isset($res['code'])) $res['code'] = -500;
        if($res['code'] > 0) $res['code'] = -$res['code'];
        if($res['code'] == 0) $res['code'] = 1;
        return $res;
    }
    
    private function build_request(array $param, $act='api'){
        $timestamp = time()*1000;
        $param = http_build_query($param);
        $paraValue = urlencode(KYAes::encrypt($param, $this->Deakey));
        $key = md5($this->agent_id.$timestamp.$this->Md5key);
        $req_url = $act == 'api' ? $this->api_url : $this->pull_url;
        return $req_url.'?agent='.$this->agent_id."&timestamp={$timestamp}&param={$paraValue}&key={$key}";
    }
}


/*加密类*/
class KYAes{
    public static function encrypt($input, $key) {
        return self::mcryptEncrypt($input,$key);
        // if (substr(PHP_VERSION, 0, 1) == '7') {
        //     return self::opensslEncrypt($input,$key);
        // }else{
        //     return self::mcryptEncrypt($input,$key);
        // }
    }
    public static function decrypt($input, $key) {
        return self::mcryptDecrypt($input,$key);
        // if (substr(PHP_VERSION, 0, 1) == '7') {
        //     return self::opensslDecrypt($input,$key);
        // }else{
        //     return self::mcryptDecrypt($input,$key);
        // }
    }
    /**
     * [encrypt description]
     * 使用mcrypt库进行加密
     * @param  [type] $input
     * @param  [type] $key
     * @return [type]
     */
    public static function mcryptEncrypt($input, $key) {
        @$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $input = self::pkcs5Pad($input, 16);
        @$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        @$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);//MCRYPT_DEV_URANDOM
        @mcrypt_generic_init($td, $key, $iv);
        @$data = mcrypt_generic($td, $input);
        @mcrypt_generic_deinit($td);
        @mcrypt_module_close($td);
        $data = base64_encode($data);
        return $data;
    }
    /**
     * [pkcs5Pad description]
     * @param  [type] $text
     * @param  [type] $blocksize
     * @return [type]
     */
    private static function pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    /**
     * [decrypt description]
     * 使用mcrypt库进行解密
     * @param  [type] $sStr
     * @param  [type] $sKey
     * @return [type]
     */
    public static function mcryptDecrypt($sStr, $sKey) {
        @$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND);//MCRYPT_DEV_URANDOM
        @$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $sKey, base64_decode($sStr), MCRYPT_MODE_ECB, $iv);
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s-1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }
    /**
     * [opensslDecrypt description]
     * 使用openssl库进行加密
     * @param  [type] $sStr
     * @param  [type] $sKey
     * @return [type]
     */
    public static function opensslEncrypt($sStr, $sKey, $method = 'AES-256-ECB'){
        $str = openssl_encrypt($sStr,$method,$sKey);
        return $str;
    }
    /**
     * [opensslDecrypt description]
     * 使用openssl库进行解密
     * @param  [type] $sStr
     * @param  [type] $sKey
     * @return [type]
     */
    public static function opensslDecrypt($sStr, $sKey, $method = 'AES-256-ECB'){
        $str = openssl_decrypt($sStr,$method,$sKey);
        return $str;
    }
}
